package com.littleken.demo.controller;

import com.littleken.demo.dto.FileInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Date;

/**
 * 文件上传下载controller
 */
@RestController
@RequestMapping("/file")
@Slf4j
public class fileController {
    private String folder = "F:\\javaproject\\security\\file";//文件保存地址

    /**
     * 文件上传接口
     * @param file
     * @return
     * @throws IOException
     */
    @PostMapping
    public FileInfo upload(MultipartFile file) throws IOException {
        log.error("file = {}",file);
        File localFile = new File(folder, new Date().getTime() + ".txt");//指定文件名字

        file.transferTo(localFile);//存储文件

        return new FileInfo(localFile.getAbsolutePath());//返回文件保存的绝对路径
    }

    /**
     * 文件下载
     * @param id
     * @param request
     * @param response
     * @throws Exception
     */
    @GetMapping("/{id}")
    public void download(@PathVariable String id, HttpServletRequest request, HttpServletResponse response) throws Exception {

        //在括号中声明的流，jdk会自动关闭
        try (InputStream inputStream = new FileInputStream(new File(folder, id + ".txt"));
             OutputStream outputStream = response.getOutputStream();) {

            response.setContentType("application/x-download");
            response.addHeader("Content-Disposition", "attachment;filename=test.txt");//指定下载文件的名字

            IOUtils.copy(inputStream, outputStream);//让用户下载文件
            outputStream.flush();
        }
    }
}


